package com.yunfeng.web.test;

import com.fang.openapi.consts.PType;
import com.fang.openapi.dto.ReturnGenericDTO;
import com.fang.openapi.dto.auth.AuthDTO;
import com.fang.openapi.dto.auth.CompanyKeyUnit;
import com.fang.openapi.dto.house.HouseReturnDTO;
import com.fang.openapi.http.exception.HttpProcessException;
import com.fang.openapi.service.Auth;
import com.fang.openapi.service.HouseManager;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class fang {

    public static HouseManager manager;

    public static void main(String[] args) {
        CompanyKeyUnit keyUnit = new CompanyKeyUnit();
        keyUnit.setKeyId((long) 10271);
        keyUnit.setSecret("de5758a2c0b142039cafab38ce1d9c83");

        Auth agent = new Auth(keyUnit, "http://openapi.agentn.fang.com");

//        System.out.println(EncryptDES("147258", "de5758a2"));
        //authDTO需要缓存，以供下次调接口直接使用，具体要求参加接口文档
        try {
            ReturnGenericDTO<AuthDTO> authDTO = agent.applyToken("yfdc2586", "147258");
            System.out.println(authDTO.getData().toString());
//            manager = new HouseManager(keyUnit);
//            ReturnGenericDTO <HouseReturnDTO> save = manager.save(authDTO.getData(), dto, PType.SFB);
        } catch (HttpProcessException e) {
            System.out.println(e.toString());
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String EncryptDES(String encryptString, String encryptKey){
        byte[] key = new byte[0];
        Base64 base64 = new Base64();
        byte[] src = null;
        try {
            key = encryptKey.getBytes("UTF-8");
            DESKeySpec dks = new DESKeySpec(key);

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(dks);

            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

            IvParameterSpec iv = new IvParameterSpec(encryptKey.getBytes("UTF-8"));
            cipher.init(Cipher.ENCRYPT_MODE, securekey, iv);

            src = encryptString.getBytes("UTF-8");
            src = cipher.doFinal(src);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return new String(base64.encode(src));
    }
}
